<?php
/*
	[Bidcms.Com!] (C)2009-2011 Bidcms.Com.
	This is NOT a freeware, use is subject to license terms

	$Id: model.class.php 2010-08-24 10:42 $
*/

if(!defined('IN_BIDCMS')) {
	exit('Access Denied');
}
class model
{

	public $fields=array();
	public $table = '';
	public $db;
	public $prefix = '';
	public $db_index = 'store';
	private static $class_key;
    public $validate = array();
	public $custom_fields='';
	public function __construct(){
		$this->init_db();
	}
	public function init_db(){
		global $db_config;
		$this->db_index=isset($db_config[$this->db_index])?$this->db_index:'store';
		if(!isset(self::$class_key['db'.$this->db_index])){
			self::$class_key['db'.$this->db_index]=new db_pdo($db_config[$this->db_index]['host'],$db_config[$this->db_index]['user'],$db_config[$this->db_index]['passwd'],$db_config[$this->db_index]['name']);
		}
		$this->db=self::$class_key['db'.$this->db_index];
	}
	function table($table){
		$this->table = $table;
		return $this;
	}
	function fields($fields){
		if(is_string($fields)){
			$fields = explode(',', $fields);
		}
		$this->custom_fields = '`'.implode('`,`',$fields).'`';
		return $this;
	}
	function exec_sql($sql){
		$sql=sprintf($sql,tname($this->table,$this->db_index));
		$rows=$this->db->exec($sql); //insert无法返回键值 ，只能显示影响的行数
		return $rows;
	}
	function get_sql($sql){
		$sql=sprintf($sql,tname($this->table,$this->db_index));
		$this->db->query($sql);
		$list=$this->db->fetchAll();
		return $list;
	}
	//取出一条数据
	//防sql注入container 值如：array('a=? and b=?',array(1,3))
	function get_one($container=array(),$order='',$showpage=array())
	{
		$sf=trim(isset($container[0])?$container[0]:'');
        $sv=isset($container[1])?$container[1]:array();
		if(!empty($this->custom_fields)){
			$field=$this->custom_fields;
		} else {
			if(!empty($this->fields)){
                $field=array_keys($this->fields);
				$field='`'.implode('`,`',$field).'`';
			} else {
				$field='*';
			}
		}

		$sql="select ".$field." from ".tname($this->table,$this->db_index);
		if(!empty($sf) && !empty($sv)){
			$sql.=' where 1 '.$sf;
		}
        
		if(isset($showpage['current_page'])){
			$current_page=intval($showpage['current_page']);
			$sql.=" limit ".$current_page.",1";
		}
		$sql.=' '.$order;
      
		$this->db->prepare($sql);
		$r = $this->db->execute($sv);
        if(!$r){
			$error=$this->db->errorInfo();
			die('error:'.$error[2].'('.$error[1].')');
		}
		return $this->db->fetch();
	}
	//取出多条数据并带分页
	//isshow是否显示分页,current_page 当前页 page_size 每页数量 url 下一页链接页面会自动加page参数 index 返回数据是否带索引
	//$showpage=array('isshow'=>1,'current_page'=>1,'page_size'=>20,'url'=>'index.php','index'=>'id','list'=>true);
	function get_page($container=array(),$showpage=array(),$order=''){
		$sf=trim(isset($container[0])?$container[0]:'');
        $sv=isset($container[1])?$container[1]:array();
		$limit='';
		$count=0;
		if($showpage){
			if(isset($showpage['isshow']) && $showpage['isshow']==1) {
				$page_size=isset($showpage['page_size']) && $showpage['page_size']>0?$showpage['page_size']:20;
				$current_page=isset($showpage['current_page'])?$showpage['current_page']:0;
				$count=$this->get_count($container);
				$limit=" limit ".($current_page*$page_size).",".$page_size;
			} elseif(isset($showpage['current_page']) && isset($showpage['page_size'])){
				$page_size=$showpage['page_size']>0?$showpage['page_size']:20;
				$current_page=intval($showpage['current_page']);
				$limit=" limit ".($current_page*$page_size).",".$page_size;
			}
		}
		if(!empty($this->custom_fields)){
			$field=$this->custom_fields;
		} else {
			if(!empty($this->fields)){
                $field=array_keys($this->fields);
				$field='`'.implode('`,`',$field).'`';
			} else {
				$field='*';
			}
		}
		$sql="select ".$field." from ".tname($this->table,$this->db_index);
		if(!empty($sf)){
			$sql.=' where 1 '.$sf;
		}
		$sql.=' '.$order;
		$sql.=" ".$limit;
        
		$this->db->prepare($sql);
		$r = $this->db->execute($sv);
        if(!$r){
			$error=$this->db->errorInfo();
			die('error:'.$error[2].'('.$error[1].')');
		}
		$result=$this->db->fetchAll();
		
       if(isset($showpage['index']) && !empty($showpage['index'])){
			$list=array();
            if(isset($showpage['list'])){
              foreach($result as $k=>$v){
                  $list[$v[$showpage['index']]][]=$v;
              }
            } else {
              foreach($result as $k=>$v){
                  $list[$v[$showpage['index']]]=$v;
              }
            }
			$result=$list;
		}
		if(isset($showpage['isshow']) && $showpage['isshow']==1) {
			return array('page'=>$count,'data'=>$result);
		}
		return $result;
	}
	//取出总数
	function get_count($container = array())
	{
		$sf=trim(isset($container[0])?$container[0]:'');
        $sv=isset($container[1])?$container[1]:array();
		$sql="select count(*) as total from ".tname($this->table,$this->db_index);

		if(!empty($sf)){
			$sql.=' where 1 '.$sf;
		}
		$this->db->prepare($sql);
		$r = $this->db->execute($sv);
        if(!$r){
			$error=$this->db->errorInfo();
			die('error:'.$error[2].'('.$error[1].')');
		}
		$count=$this->db->fetch();
		return intval($count['total']);
	}
	//取出指定字段和
	function get_sum($field,$container=array(),$showpage=array())
	{
		$sf=trim(isset($container[0])?$container[0]:'');
        $sv=isset($container[1])?$container[1]:array();
		$sql="select sum(`".$field."`) as total from ".tname($this->table,$this->db_index);

		if(!empty($sf)){
			$sql.=' where 1 '.$sf;
		}
		if(isset($showpage['current_page']) && isset($showpage['page_size'])){
			$page_size=$showpage['page_size']>0?$showpage['page_size']:20;
			$current_page=intval($showpage['current_page']);
			$sql.=" limit ".($current_page*$page_size).",".$page_size;
		}
		$this->db->prepare($sql);
		$this->db->execute($sv);
		$sum=$this->db->fetch();
		return intval($sum['total']);
	}
	//插入数据
	function insert_data($data=array(),$debug=false)
	{
		$data=!empty($data)?$data:$this->dataset;
        if(!empty($this->fields)){
          $fields=array_keys($this->fields);
          foreach($this->fields as $k=>$v){
              if(isset($data[$k])){ //排除非空字段
                  $key[]='`'.$k.'`';
                  $kval[]=':bidcms_'.$k;
                  $format_val=$data[$k];
                  if(isset($this->fields[$k]['format']) && !empty($this->fields[$k]['format'])){
                      $format_val=$this->fields[$k]['format']($data[$k]);
                  }
                  $val[':bidcms_'.$k]=$format_val;
              }
          }
        } else {
          foreach($data as $k=>$v){
              if(isset($data[$k])){ //排除非空字段
                  $key[]='`'.$k.'`';
                  $kval[]=':bidcms_'.$k;
                  $val[':bidcms_'.$k]=$v;
              }
          }
        }
		if(empty($key)){
			return 0;
		}
		$sql="insert into ".tname($this->table,$this->db_index)."(".implode(',',$key).") values(".implode(',',$kval).")";
		
		$this->db->prepare($sql);
		$r=$this->db->execute($val);
		if(!$r){
			$error=$this->db->errorInfo();
			die('error:'.$error[2].'('.$error[1].')');
		}
		unset($sql,$key,$val,$kval);
		return $this->db->lastInertId();
	}
	//更新数据
	function update_data($container,$data=array())
	{
		$sf=trim(isset($container[0])?$container[0]:'');
        if(substr($sf,0,3)!='and'){
          return 0;
        }
		if(!empty($sf) && is_string($sf)){
			$sv=isset($container[1])?$container[1]:array();
			$data=!empty($data)?$data:$this->dataset;
            if(!empty($this->fields)){
              $fields=array_keys($this->fields);
              foreach($data as $k=>$v){
                  if(in_array($k,$fields)){
                      $key[]='`'.$k.'`=:bidcms_'.$k;
                      $format_val=$v;
                      if(isset($this->fields[$k]['format']) && !empty($this->fields[$k]['format'])){
                          $format_val=$this->fields[$k]['format']($v);
                      }
                      $val[':bidcms_'.$k]=$format_val;
                  }
              }
            } else {
              foreach($data as $k=>$v){
                  $key[]='`'.$k.'`=:bidcms_'.$k;
                  $val[':bidcms_'.$k]=$v;
              }
            }
			if(empty($key)){
				return 0;
			}
			$sql="update ".tname($this->table,$this->db_index)." set ".implode(',',$key).' where 1 '.$sf;
			$val=array_merge($val,$sv);
			$this->db->prepare($sql);
			$this->db->execute($val);
			unset($sql,$key,$val);
			return $this->db->rowCount();
		}
		return 0;

	}
	//删除数据
	function delete_data($container)
	{
		$sf=trim(isset($container[0])?$container[0]:'');
        if(substr($sf,0,3)!='and'){
          return 0;
        }
		$sv=isset($container[1])?$container[1]:array();
		if(!empty($sf) && is_string($sf) && strlen($sf)>6){
			$sql="delete from ".tname($this->table,$this->db_index)." where 1 ".$sf;
			$this->db->prepare($sql);
			$this->db->execute($sv);
			return $this->db->rowCount();
		}
		return 0;
	}
	function get_list_lang($lang_id=0){
		$list=array();
		if($this->definition['multilang'] && isset($this->fields['language_id']) && $lang_id>0){
			$container=array(' and language_id=:lang_id',array(':lang_id'=>$lang_id));
			$list=$this->get_page($container);
		}
		return $list;
	}
	function get_list_join_ids($ids,$lang_id=0){
        $ids = !is_array($ids)?explode(',',$ids):$ids;
        foreach($ids as $k=>$v){
          if(empty($v)){
            unset($ids[$k]);
          }
        }
		$list=array();
		if($this->definition['join'] && $ids && is_array($ids)){
			$container=array(' and '.$this->definition['join'].' in ('.implode(',',$ids).')',array());
			$list=$this->get_page($container);
		}
		return $list;
	}
	function get_list_join_id($id,$is_mutil=false){
		$list=array();
		if(!empty($this->definition['join']) && !empty($id)){
			$container=array(' and '.$this->definition['join'].'=:id',array(':id'=>$id));
			$list=$this->get_page($container);
		}
		return $list;
	}
	public function get_list_primary_ids($ids){
        $ids = !is_array($ids)?explode(',',$ids):$ids;
        foreach($ids as $k=>$v){
          if(empty($v)){
            unset($ids[$k]);
          }
        }
		$list=array();
        if(count($ids)>0 && !empty($this->definition['primary'])){
          $container=array(' and '.$this->definition['primary'].' in ('.implode(',',$ids).')',array());
          $list=$this->get_page($container);
        }
		return $list;
	}

	public function get_info_primary_id($id){
		$info=array();
		if($id>0 && !empty($this->definition['primary'])){
			$info=$this->get_one(array('and '.$this->definition['primary'].'=:id',array(':id'=>$id)));
		}
		return $info;
	}
	public function get_info_join_id($id){
		$info=array();
		if($id>0 && !empty($this->definition['join'])){
			$info=$this->get_one(array('and '.$this->definition['join'].'=:id',array(':id'=>$id)));
		}
		return $info;
	}
}
